package com.wenbo.ocr.utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;

/**
 * @Author wenbo
 * @Date 2023/10/18 22:03
 **/
public class IOUtils {

    public IOUtils() {
    }

    public static void extractJarResource(String source, File target) throws IOException {
        InputStream in = IOUtils.class.getResourceAsStream(source);

        try {
            FileOutputStream out = new FileOutputStream(target);

            try {
                byte[] buffer = new byte[2048];

                int len;
                while((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                    out.flush();
                }
            } catch (Throwable var8) {
                try {
                    out.close();
                } catch (Throwable var7) {
                    var8.addSuppressed(var7);
                }

                throw var8;
            }

            out.close();
        } catch (Throwable var9) {
            if (in != null) {
                try {
                    in.close();
                } catch (Throwable var6) {
                    var9.addSuppressed(var6);
                }
            }

            throw var9;
        }

        if (in != null) {
            in.close();
        }

    }

    public static void write(BufferedImage image, String formatName, File file) {
        try {
            ImageIO.write(image, formatName, file);
        } catch (Exception var4) {
            LogUtils.printMessage((String)null, var4, LogUtils.Level.ERROR);
        }

    }

    public static void write(byte[] byteArray, File file) {
        try {
            FileOutputStream outputStream = new FileOutputStream(file);

            try {
                outputStream.write(byteArray);
            } catch (Throwable var6) {
                try {
                    outputStream.close();
                } catch (Throwable var5) {
                    var6.addSuppressed(var5);
                }

                throw var6;
            }

            outputStream.close();
        } catch (Exception var7) {
            LogUtils.printMessage((String)null, var7, LogUtils.Level.ERROR);
        }

    }

    public static void write(String base64, File file) {
        try {
            write(Base64.getDecoder().decode(base64), file);
        } catch (Exception var3) {
            LogUtils.printMessage((String)null, var3, LogUtils.Level.ERROR);
        }

    }

    public static BufferedImage read(String imageFile) throws IOException {
        return ImageIO.read(new File(imageFile));
    }
}
